package com.whfc.fvs.service.manager;

import com.alibaba.fastjson.JSON;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.HttpUtil;
import com.whfc.common.vs.ezviz.EzvizApi;
import com.whfc.common.vs.ezviz.enums.EzvizResponseCode;
import com.whfc.common.vs.imou.ImouApi;
import com.whfc.fvs.dao.FvsSettingMapper;
import com.whfc.fvs.dto.FvsSettingDTO;
import com.whfc.fvs.enums.VsPlatform;
import com.whfc.fvs.redis.EzvizApiTokenRedisDao;
import com.whfc.fvs.redis.ImouApiTokenRedisDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 监控 token Mgr
 *
 * @author qzexing
 * @version 1.0
 * @date 2021/10/18 16:35
 */
@Component
public class FvsTokenMgr {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value(value = "${fvs.token.ezviz.url}")
    private String getEzvizTokenUrl;

    @Value(value = "${fvs.token.imou.url}")
    private String getImouTokenUrl;

    @Value(value = "${fvs.token.profile.type}")
    private String profileType;

    @Value("${whfc.default.demo.project}")
    private Integer defaultDeptId;

    @Value("${spring.profiles.active}")
    private String profile;

    @Autowired
    private FvsSettingMapper fvsSettingMapper;

    @Autowired
    private EzvizApiTokenRedisDao ezvizApiTokenRedisDao;

    @Autowired
    private ImouApiTokenRedisDao imouApiTokenRedisDao;

    /**
     * 获取萤石云AccessToken
     *
     * @return AccessToken
     */
    public String getEzvizAccessToken(Integer deptId) {
        try {
            if (profileType.equals(profile)) {
                FvsSettingDTO fvsSetting = getFvsSetting(deptId, VsPlatform.HIK_EZVIZ);
                String accessToken = ezvizApiTokenRedisDao.getAccessToken(fvsSetting.getAppKey());
                if (StringUtils.isBlank(accessToken)) {
                    accessToken = EzvizApi.getAccessToken(fvsSetting.getAppKey(), fvsSetting.getAppSecret());
                }
                return accessToken;
            } else {
                String url = getEzvizTokenUrl + "/" + deptId;
                String resultStr = HttpUtil.doGet(url);
                Result result = JSON.parseObject(resultStr, Result.class);
                if (result == null || !EzvizResponseCode.SUCCESS.getCode().equals(result.getCode())) {
                    throw new BizException(ResultEnum.FAILURE.getCode(), "获取OpenApi萤石云Token失败.");
                }
                return result.getData().toString();
            }
        } catch (Exception e) {
            logger.warn("获取OpenApi萤石云Token失败", e);
            throw new BizException(ResultEnum.FAILURE.getCode(), "获取OpenApi萤石云Token失败.");
        }
    }

    /**
     * 初始化乐橙token
     *
     * @param imouApi 乐橙API
     */
    public String getImouAccessToken(ImouApi imouApi, Integer deptId) {
        try {
            if (profileType.equals(profile)) {
                String appKey = imouApi.getAppKey();
                String accessToken = imouApiTokenRedisDao.getAccessToken(appKey);
                if (StringUtils.isBlank(accessToken)) {
                    accessToken = imouApi.getAccessToken();
                    imouApiTokenRedisDao.setAccessToken(appKey, accessToken);
                }
                return accessToken;
            } else {
                String url = getImouTokenUrl + "/" + deptId;
                String resultStr = HttpUtil.doGet(url);
                Result result = JSON.parseObject(resultStr, Result.class);
                if (result == null || !ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
                    throw new BizException(ResultEnum.FAILURE.getCode(), "获取OpenApi乐橙云Token失败.");
                }
                return result.getData().toString();
            }
        } catch (Exception e) {
            logger.error("获取OpenApi乐橙云Token失败", e);
            throw new BizException(ResultEnum.FAILURE.getCode(), "获取OpenApi乐橙云Token失败.");
        }
    }


    /**
     * 获取监控平台配置
     *
     * @param deptId   组织架构ID
     * @param platform 平台类型
     * @return 平台配置
     */
    public FvsSettingDTO getFvsSetting(Integer deptId, VsPlatform platform) {
        FvsSettingDTO fvsSetting = fvsSettingMapper.selectAppKeySecret(deptId, platform.getValue());
        if (fvsSetting == null) {
            fvsSetting = fvsSettingMapper.selectAppKeySecret(defaultDeptId, platform.getValue());
        }
        return fvsSetting;
    }


}
